"""
配置加载器 - 从YAML文件加载配置

使用方式：
    from config_loader import (
        POSITION_CALCULATOR_CONFIG,
        TRADE_PROTECTOR_CONFIG,
        STRATEGY_CONFIG,
        BUY_PARAMS,
        SELL_PARAMS,
        MARKET_CAP_THRESHOLD,
        TREND_FILTER_CONFIG,
        BACKTEST_CONFIG,
        LOGGING_CONFIG
    )
"""

import os
from typing import Dict, Any

# 尝试导入yaml，如果失败则设置标志
try:
    import yaml
    YAML_AVAILABLE = True
except ImportError:
    YAML_AVAILABLE = False
    print("警告: yaml模块未安装，技术形态分析功能将被禁用")
    print("提示: 运行 'pip install pyyaml' 安装yaml模块以启用该功能")

# 配置文件路径
CONFIG_FILE = os.path.join(os.path.dirname(__file__), 'config', 'config.yaml')
TECHNICAL_PATTERNS_FILE = os.path.join(os.path.dirname(__file__), 'config', 'technical_patterns.yaml')


class ConfigLoader:
    """配置加载器"""
    
    def __init__(self, config_file: str = CONFIG_FILE, technical_patterns_file: str = TECHNICAL_PATTERNS_FILE):
        """
        初始化配置加载器
        
        Args:
            config_file: 配置文件路径
            technical_patterns_file: 技术形态配置文件路径
        """
        self.config_file = config_file
        self.technical_patterns_file = technical_patterns_file
        self._config = None
        self._technical_patterns = None
        self._load_config()
        self._load_technical_patterns()
    
    def _load_config(self):
        """加载配置文件"""
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                self._config = yaml.safe_load(f)
        except FileNotFoundError:
            raise FileNotFoundError(f"配置文件不存在: {self.config_file}")
        except yaml.YAMLError as e:
            raise ValueError(f"配置文件格式错误: {e}")
    
    def _load_technical_patterns(self):
        """加载技术形态配置文件"""
        # 如果yaml模块不可用，直接返回禁用配置
        if not YAML_AVAILABLE:
            self._technical_patterns = {'upper_shadow': {'enabled': False}}
            return
        
        try:
            with open(self.technical_patterns_file, 'r', encoding='utf-8') as f:
                self._technical_patterns = yaml.safe_load(f)
        except FileNotFoundError:
            print(f"警告: 技术形态配置文件不存在: {self.technical_patterns_file}，将禁用技术形态分析")
            self._technical_patterns = {'upper_shadow': {'enabled': False}}
        except Exception as e:
            # 捕获所有异常（包括 yaml.YAMLError 和其他未知错误）
            print(f"警告: 技术形态配置加载失败: {e}，将禁用技术形态分析")
            self._technical_patterns = {'upper_shadow': {'enabled': False}}
    
    def reload(self):
        """重新加载配置文件（支持热重载）"""
        self._load_config()
        self._load_technical_patterns()
    
    @property
    def position_calculator(self) -> Dict[str, Any]:
        """获取仓位计算器配置"""
        return self._config['position_calculator']
    
    @property
    def trade_protector(self) -> Dict[str, Any]:
        """获取交易保护器配置"""
        return self._config['trade_protector']
    
    @property
    def strategy(self) -> Dict[str, Any]:
        """获取策略配置"""
        return self._config['strategy']
    
    @property
    def market_cap_threshold(self) -> Dict[str, Any]:
        """获取市值分类阈值"""
        return self._config['market_cap_threshold']
    
    def get_buy_params(self) -> Dict[str, Any]:
        """
        获取买入参数配置
        
        Returns:
            包含买入策略所有参数的字典
        """
        return {
            'normal_strategy': {
                'volume_classification': self._config['normal_strategy_volume'],
                'vol_ma20_multiplier': self._config['normal_strategy_vol_ma20']
            },
            'strong_stock_strategy': self._config['strong_stock_strategy'],
            'market_cap_threshold': self._config['market_cap_threshold']
        }
    
    def get_sell_params(self) -> Dict[str, Any]:
        """
        获取卖出参数配置
        
        Returns:
            包含卖出条件所有参数的字典
        """
        return {
            'high_shrink': self._config['sell_high_shrink'],
            'extreme_volume': self._config['sell_extreme_volume'],
            'volume_lag': self._config['sell_volume_lag'],
            'break_ma5': self._config['sell_break_ma5'],
            'market_cap_threshold': self._config['market_cap_threshold']
        }
    
    def get_backtest_config(self) -> Dict[str, Any]:
        """
        获取回测配置（分时回测）
        
        Returns:
            回测配置字典
        """
        return self._config['backtest']
    
    @property
    def logging_config(self) -> Dict[str, Any]:
        """获取日志配置"""
        return self._config['log']
    
    @property
    def technical_patterns(self) -> Dict[str, Any]:
        """获取技术形态配置"""
        return self._technical_patterns
    
    def get_technical_patterns_config(self) -> Dict[str, Any]:
        """
        获取技术形态配置（完整版）
        
        Returns:
            技术形态配置字典
        """
        return self._technical_patterns


# ============================================
# 全局单例配置加载器
# ============================================

_config_loader = None

def get_config_loader() -> ConfigLoader:
    """获取全局配置加载器实例（单例模式）"""
    global _config_loader
    if _config_loader is None:
        _config_loader = ConfigLoader()
    return _config_loader


# ============================================
# 便捷导出（兼容原有导入方式）
# ============================================

# 仓位管理配置
POSITION_CALCULATOR_CONFIG = get_config_loader().position_calculator
TRADE_PROTECTOR_CONFIG = get_config_loader().trade_protector

# 策略配置
STRATEGY_CONFIG = get_config_loader().strategy
MARKET_CAP_THRESHOLD = get_config_loader().market_cap_threshold

# 买入卖出参数
BUY_PARAMS = get_config_loader().get_buy_params()
SELL_PARAMS = get_config_loader().get_sell_params()

# 趋势过滤配置（硬指标）
TREND_FILTER_CONFIG = get_config_loader()._config.get('trend_filter', {})

# 止损配置（全局）
STOP_LOSS_CONFIG = get_config_loader()._config.get('stop_loss', {})

# 回测配置（统一配置）
BACKTEST_CONFIG = get_config_loader().get_backtest_config()

# 日志配置
LOGGING_CONFIG = get_config_loader().logging_config

# 技术形态配置
TECHNICAL_PATTERNS_CONFIG = get_config_loader().get_technical_patterns_config()


# ============================================
# 热重载支持
# ============================================

def reload_config():
    """
    重新加载配置文件
    
    使用场景：
        在不重启程序的情况下，重新加载配置文件
    
    示例：
        from config_loader import reload_config
        reload_config()
    """
    global _config_loader, POSITION_CALCULATOR_CONFIG, TRADE_PROTECTOR_CONFIG
    global STRATEGY_CONFIG, MARKET_CAP_THRESHOLD, BUY_PARAMS, SELL_PARAMS
    global TREND_FILTER_CONFIG, BACKTEST_CONFIG, LOGGING_CONFIG, TECHNICAL_PATTERNS_CONFIG
    
    # 重新加载
    _config_loader.reload()
    
    # 更新全局变量
    POSITION_CALCULATOR_CONFIG = _config_loader.position_calculator
    TRADE_PROTECTOR_CONFIG = _config_loader.trade_protector
    STRATEGY_CONFIG = _config_loader.strategy
    MARKET_CAP_THRESHOLD = _config_loader.market_cap_threshold
    BUY_PARAMS = _config_loader.get_buy_params()
    SELL_PARAMS = _config_loader.get_sell_params()
    TREND_FILTER_CONFIG = _config_loader._config.get('trend_filter', {})
    BACKTEST_CONFIG = _config_loader.get_backtest_config()
    LOGGING_CONFIG = _config_loader.logging_config
    TECHNICAL_PATTERNS_CONFIG = _config_loader.get_technical_patterns_config()
    
    print("✅ 配置文件已重新加载（包含趋势过滤配置）")


def load_technical_config():
    """
    快捷加载技术形态配置
    
    使用场景：
        在技术引擎初始化时加载配置
    
    示例：
        from config_loader import load_technical_config
        config = load_technical_config()
        engine = TechnicalEngine(config)
    
    Returns:
        技术形态配置字典
    """
    return get_config_loader().get_technical_patterns_config()


if __name__ == '__main__':
    # 测试配置加载
    print("=" * 60)
    print("配置加载器测试")
    print("=" * 60)
    
    loader = get_config_loader()
    
    print("\n1. 仓位计算器配置:")
    print(f"   基准仓位: {loader.position_calculator['base_position']}")
    
    print("\n2. 交易保护器配置:")
    print(f"   冷静期: {loader.trade_protector['repeat_buy_cooldown_hours']}小时")
    
    print("\n3. 策略配置:")
    print(f"   价格位置阈值: {loader.strategy['price_position_threshold']}")
    
    print("\n4. 市值阈值:")
    print(f"   大盘股: >{loader.market_cap_threshold['large']}亿")
    print(f"   小盘股: <{loader.market_cap_threshold['small']}亿")
    
    print("\n5. 买入参数:")
    buy_params = loader.get_buy_params()
    print(f"   高位强势策略-大盘股均线间距: {buy_params['strong_stock_strategy']['ma_spacing']['large']}%")
    
    print("\n6. 卖出参数:")
    sell_params = loader.get_sell_params()
    print(f"   条件A-大盘股量比: <{sell_params['high_shrink']['large']['volume_ratio']}")
    
    print("\n7. 回测配置:")
    backtest_config = loader.get_backtest_config()
    print(f"   初始资金: {backtest_config['initial_capital']}元")
    print(f"   手续费率: {backtest_config['commission_rate']*10000}‰")
    print(f"   滑点模型: 动态分层滑点")
    print(f"   - 大盘股默认: {backtest_config['slippage']['large_cap']['default']*100}%")
    print(f"   - 中盘股默认: {backtest_config['slippage']['mid_cap']['default']*100}%")
    print(f"   - 小盘股默认: {backtest_config['slippage']['small_cap']['default']*100}%")
    
    print("\n8. 技术形态配置:")
    tech_config = loader.get_technical_patterns_config()
    if tech_config.get('upper_shadow', {}).get('enabled', False):
        print(f"   上影线分析: 已启用")
        sell_config = tech_config['upper_shadow']['sell_signals']
        print(f"   - 大盘股上影线阈值: {sell_config['large_cap']['shadow_ratio']:.1%}")
        print(f"   - 中盘股上影线阈值: {sell_config['medium_cap']['shadow_ratio']:.1%}")
        print(f"   - 小盘股上影线阈值: {sell_config['small_cap']['shadow_ratio']:.1%}")
        print(f"   卖出确认阈值: {tech_config['upper_shadow']['strength_threshold']['sell_confirm']}分")
        print(f"   紧急卖出阈值: {tech_config['upper_shadow']['strength_threshold']['sell_emergency']}分")
    else:
        print(f"   上影线分析: 未启用")
    
    print("\n" + "=" * 60)
    print("✅ 配置加载测试完成")
    print("=" * 60)

